# coding=utf-8
# 调用惠仁的处方审核

import json
import logging
import datetime, time
import cx_Oracle
from api import app
from flask import request, abort
import xml.dom.minidom

import process
from api.oldaudit import client
from modules.schema.utils import getdata, DottableDict
from modules.huirenaudit import HuiRenAudit
from modules.xinghuaaudit import XingHuaAudit

LOG = logging.getLogger("presauditbyhxjl")

def yaoshi_verify(base_data, cf_data, jbzd_data, check_type):
    # 审方
    base_xml = process.xml_opbase(cf_data[0])
    details_xml = process.xml_opdetail(base_data[0], cf_data, jbzd_data, check_type)
    LOG.info("base_xml:%s, details_xml:%s", base_xml, details_xml)
    try:
        ret = client.service.Query(8001, base_xml, details_xml)
    except Exception,e:
        LOG.error('yaoshi_verify Exception: %s', e)
        ret = {
            'QueryResult': 1,
            'outXML': '',
            'pharmacist': 0
        }
        ret = DottableDict(ret)

    LOG.info("yaoshi_verify ret:%s", ret)
    return ret

# 保存处方id和审核结果(惠仁旧审核引擎)
def save_pres_old(pres_id,ret_data):
    LOG.info("pres_id: %s, ret_data: %s", pres_id, ret_data)
    DOMTree = xml.dom.minidom.parseString(ret_data.outXML)
    # brief
    brief = ''
    data_item = DOMTree.getElementsByTagName("brief")
    for item in data_item:
        if item.childNodes:
            brief = item.childNodes[0].nodeValue

    # result_data
    result_data = ''
    data_item = DOMTree.getElementsByTagName("result_data")
    for item in data_item:
        if item.childNodes:
            result_data = item.childNodes[0].nodeValue

    audit_data = HuiRenAudit(
        pres_id = str(pres_id),
        QueryResult = ret_data.QueryResult,
        brief = brief,
        result_data = result_data,
        outXML = ret_data.outXML,
        pharmacist = ret_data.pharmacist,
        created_at = int(time.time() * 1000),
        updated_at = int(time.time() * 1000)
    )
    audit_data.save()

# 保存新引擎审核结果
def save_pres_new(pres_id, audit_data):
    LOG.info("pres_id: %s, audit_data: %s", pres_id, audit_data)

    audit_data = XingHuaAudit(
        pres_id = str(pres_id),
        code = int(getdata(audit_data['code'])),
        phar_id = str(audit_data['phar_id']).decode('unicode_escape'),
        results = str(audit_data['results']).decode('unicode_escape'),
        med_info = str(audit_data['med_info']).decode('unicode_escape'),
        created_at = int(time.time() * 1000),
        updated_at = int(time.time() * 1000)
    )
    audit_data.save()

# 门诊 审方
@app.route('/prescription/oldaudit', methods=['POST'])
def oldaudit():
    """
    处方审核
    """
    LOG.info("oldaudit: %s", request.get_json())
    outpatient_pres_start_time = time.time()
    LOG.info('outpatient_pres_start_time:%s', outpatient_pres_start_time)

    mydata = request.get_json()
    base_data = mydata['base_data']
    cf_data = mydata['cf_data']
    jbzd_data = mydata['jbzd_data']
    cf_id = mydata['cf_id']         # 我们库的处方mongodb id
    audit_data = mydata['audit_data']   # 我们新审核引擎的审核结果
    
    # 惠仁旧审方
    ret_data = yaoshi_verify(base_data, cf_data, jbzd_data, 1)
    LOG.info("ret_data: %s", ret_data)

    outpatient_pres_end_time = time.time()
    LOG.info('outpatient_pres_end_time:%s', outpatient_pres_end_time)
    LOG.info('outpatient_pres_spend_time:%s', outpatient_pres_end_time-outpatient_pres_start_time)

    # 保存我们新引擎审核结果
    save_pres_new(cf_id, audit_data)
    # 保存惠仁旧审核结果
    save_pres_old(cf_id, ret_data)
    if ret_data.QueryResult == 0 or ret_data.QueryResult == 1:
        LOG.info('自通处方号：%s', cf_data[0][0])

    status = ret_data.QueryResult
    return str(status)
